import 'package:ct_pa_majordomo/config/theme_vars.dart';
import 'package:ct_pa_majordomo/pages/device/lock/api.dart';
import 'package:ct_pa_majordomo/utils/stacker.dart';
import 'package:ct_pa_majordomo/widgets/button/index.dart';
import 'package:ct_pa_majordomo/widgets/normal_scaffold/index.dart';
import 'package:ct_pa_majordomo/utils/nfc_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

class AddICCard extends StatefulWidget {
  final Map<String, dynamic> renter;
  final int lockId;

  const AddICCard({
    super.key,
    required this.renter,
    required this.lockId,
  });

  @override
  State<AddICCard> createState() => _AddICCardState();
}

class _AddICCardState extends State<AddICCard> {
  bool _isScanning = false;
  String? _cardNumber;

  @override
  void initState() {
    super.initState();
    _checkNfcAvailability();
  }

  // 检查NFC是否可用
  Future<void> _checkNfcAvailability() async {
    bool isAvailable = await NFCUtils.checkNFCAvailability(context);
    if (!isAvailable && mounted) {
      Stacker.pop();
    }
  }

  // 开始扫描NFC卡
  Future<void> _startNfcScan() async {
    if (_isScanning) return;

    setState(() {
      _isScanning = true;
      _cardNumber = null;
    });

    try {
      String? cardNumber = await NFCUtils.startNFCScanning();
      
      if (cardNumber != null) {
        setState(() {
          _cardNumber = cardNumber;
        });
        
        // 调用后端接口保存IC卡信息
        await _saveICCard(cardNumber);
      }
    } catch (e) {
      debugPrint('NFC扫描出错: $e');
      EasyLoading.showError('扫描失败，请重试');
    } finally {
      if (mounted) {
        setState(() {
          _isScanning = false;
        });
      }
    }
  }

  // 保存IC卡信息
  Future<void> _saveICCard(String cardNumber) async {
    try {
      EasyLoading.show(status: '正在保存...');
      await lockApi.addICCard({
        'lockId': widget.lockId,
        'cardNumber': cardNumber,
        'userId': widget.renter['userId'],
        'userName': widget.renter['name'],
      });
      
      EasyLoading.showSuccess('发卡成功');
      if (mounted) {
        Stacker.pop(true);
      }
    } catch (e) {
      debugPrint('保存IC卡信息出错: $e');
      EasyLoading.showError('保存失败，请重试');
    }
  }

  @override
  void dispose() {
    // 释放NFC资源
    NFCUtils.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return NormalScaffold(
      title: '发卡',
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              Icons.nfc,
              size: 80,
              color: ThemeVars.colorPrimary,
            ),
            const SizedBox(height: 20),
            Text(
              _isScanning ? '请将IC卡贴近手机背面' : '点击下方按钮开始扫描IC卡',
              style: const TextStyle(fontSize: 16),
            ),
            if (_cardNumber != null) ...[
              const SizedBox(height: 20),
              Text(
                '卡号：$_cardNumber',
                style: const TextStyle(
                  fontSize: 16,
                  color: ThemeVars.colorSuccess,
                ),
              ),
            ],
            const SizedBox(height: 40),
            Button(
              onPressed: _isScanning ? null : _startNfcScan,
              child: Text(_isScanning ? '正在扫描...' : '开始扫描'),
            ),
          ],
        ),
      ),
    );
  }
} 